﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace 客户端
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建sock对象
            Socket clientSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            //连接指定ip.port
            clientSocket.Connect(IPAddress.Parse("127.0.0.1"),11818);
            Console.WriteLine("连接服务器");
            //发送消息
            Console.WriteLine("输入要发送的信息");
            
            Thread trevice=new Thread((s) =>
            {
                Socket client = s as Socket;
                int len = 0;
                byte[] bs1 = new byte[1024];

                while (true)
                {
                   
                    string str = Console.ReadLine();
                    byte[] bs = Encoding.UTF8.GetBytes(str);
                    clientSocket.Send(bs);
                    
                }
               
                
            });
            Thread sendThread=new Thread((s2) =>
            {
                int len = 0;
                byte[] bs1 = new byte[1024];
                Socket sendSocket = s2 as Socket;
                while ((len = sendSocket.Receive(bs1)) > 0)
                {
                    Console.WriteLine(Encoding.UTF8.GetString(bs1, 0, len));

                }
                
            });
            sendThread.IsBackground = true;
            sendThread.Start(clientSocket);
            trevice.IsBackground = true;
            trevice.Start(clientSocket);
            //
            //Console.WriteLine("接受来自服务器的信息");
            //bs=new byte[1024];
            //int len = clientSocket.Receive(bs);
            //Console.Write(Encoding.UTF8.GetString(bs, 0, len));
            ////while ((len=clientSocket.Receive(bs))>0)//receive此会阻塞线程
            //while(clientSocket.Available>0)
            //{
            //    len = clientSocket.Receive(bs);
            //    Console.Write(Encoding.UTF8.GetString(bs, 0, len));
                
            //}
            

            Console.ReadKey();
        }
    }
}
